package cn.haoran.modules.sys.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
/**
 * 配置消息队列中 交换机实例 队列实例
 *              0. Exchange :缺省交换机
 * 交换机种类:  1.TopicExchange :主题订阅交换机
 *              2. FanoutExchange:广播式交换机
 *
 */
public class RabbitExchangeConfig {
    //===============使用了RabbitMQ系统缺省的交换器 创建队列会默认创建一个当前队列名一样的交换机==========
    //绑定键即为队列名称
    @Bean
    public Queue helloQueue() {
        return new Queue(IExchangeState.QUEUE_HELLO);
    }

    @Bean
    public Queue userQueue() {
        return new Queue(IExchangeState.QUEUE_USER);
    }

    //===============为创建topic Exchange ==========
    @Bean
    public Queue queueEmailMessage() {
        return new Queue(IExchangeState.QUEUE_TOPIC_EMAIL,true);
    }

    @Bean
    public Queue queueUserMessages() {
        return new Queue(IExchangeState.QUEUE_TOPIC_USER,true);
    }

    @Bean
    public TopicExchange exchange() {
        return new TopicExchange(IExchangeState.EXCHANGE_TOPIC,true,true);
    }

    /**
     * 绑定路由件
     * @return
     */
    @Bean
    public Binding bindingEmailExchangeMessage() {
        // bind (队列名称)  to 交换机名 with: 路由
        //注: 当前如果为主题订阅交换机 路由键会根据类似于正则去匹配 如: *.user;info.*user 等等
        // 广播交换机只需要绑定队列和交换机 无需绑定 路由键
        return BindingBuilder
                .bind(queueEmailMessage())
                .to(exchange())
                .with("sb.*.email");
    }

    @Bean
    public Binding bindingUserExchangeMessages() {
        return BindingBuilder
                .bind(queueUserMessages())
                .to(exchange())
                .with("sb.*.user");
    }

    //===============以上是验证topic Exchange==========

    //===============以下是验证Fanout Exchange==========
    @Bean
    public Queue AMessage() {
        return new Queue("sb.fanout.A");
    }

    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange(IExchangeState.EXCHANGE_FANOUT);
    }

    @Bean
    Binding bindingExchangeA(Queue AMessage,FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(AMessage).to(fanoutExchange);
    }

    //===============以上是验证Fanout Exchange的交换器==========
}
